﻿using System;
using System.IO;
using System.Web;
using GC_RF.Domain.Abstractions.Interfaces.Helpers;

namespace GC_RF.Domain.Helpers
{
	public class HttpPostedFileManager : IHttpPostedFileManager
	{
		#region Varibles

		private readonly IFileManager _fileManager;

		#endregion

		#region Constructors

		public HttpPostedFileManager(IFileManager fileManager)
		{
			if (fileManager == null)
				throw new ArgumentNullException(string.Format("fileManager"));
			_fileManager = fileManager;
		}

		#endregion

		#region IFileManager Members

		public string SaveAs(HttpPostedFileBase file, string directoryPath)
		{
			if (file == null || !Directory.Exists(directoryPath))
				return string.Empty;

			var fileExt = _fileManager.GetFileExtByName(file.FileName);
			if (string.IsNullOrWhiteSpace(fileExt))
				return string.Empty;

			string fileName;
			string fullPath;

			do
			{
				fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExt);
				fullPath = Path.Combine(directoryPath, fileName);
			} while (File.Exists(fullPath));

			file.SaveAs(fullPath);

			return fileName;
		}

		#endregion
	}
}
